package com.org.api.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.api.admin.dao.UserMapper;
import com.org.api.admin.entity.dto.UserDto;
import com.org.api.admin.entity.vo.UserVo;
import com.org.platform.model.ResultModel;
import com.org.platform.utils.CommonUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author duheng
 * @Date 2021/11/13 17:21
 */
@Service
public class UserService extends ServiceImpl<UserMapper, UserDto> {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public ResultModel login(UserVo userVo) {
		if (CommonUtil.isNullOrEmpty(userVo.getUsername()) || CommonUtil.isNullOrEmpty(userVo.getPassword())) {
			return ResultModel.newFail("用户名或密码不能为空");
		}
		QueryWrapper<UserDto> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("LOGIN_NAME", userVo.getUsername());
		UserDto resultDto = userMapper.selectOne(queryWrapper);
		if (null == resultDto || (!CommonUtil.equals(resultDto.getPassword(), userVo.getPassword()))) {
			return ResultModel.newFail("用户名或密码错误");
		}
		Map<String, Object> result = new HashMap<>(3);
		String token = UUID.randomUUID().toString();
		stringRedisTemplate.opsForValue().set(resultDto.getLoginName(), token, 5, TimeUnit.MINUTES);
		result.put("token", token);
		result.put("loginName", resultDto.getLoginName());
		result.put("userName", resultDto.getUserName());
		return ResultModel.newSuccess(result);
	}

}
